package com.indi.gulimall.cart.interceptor;

import com.indi.common.constant.AuthConstant;
import com.indi.common.constant.CartConstant;
import com.indi.common.dto.UserInfoDTO;
import com.indi.common.to.MemberTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 拦截器
 */
public class CartInterceptor implements HandlerInterceptor {
    // 同一个线程共享数据
    public static ThreadLocal<UserInfoDTO> threadLocal = new ThreadLocal<>();

    /**
     * 执行目标方法之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        HttpSession session = request.getSession();
        MemberTO memberTO = (MemberTO) session.getAttribute(AuthConstant.SESSION_ATTR_NAME);
        if (memberTO != null) {
            // 说明用户已登录
            userInfoDTO.setUserId(memberTO.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                // 如果请求还携带了临时用户的信息，临时用户的数据也要封装起来
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoDTO.setUserKey(cookie.getValue());
                    userInfoDTO.setTempUser(true);
                }
            }
        }

        UserInfoDTO userInfoDTO1 = threadLocal.get();

        // 如果没有临时用户，则需要分配一个临时用户
        if (StringUtils.isEmpty(userInfoDTO.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoDTO.setUserKey(uuid);
        }
        // 方法执行之前，将数据放到ThreadLocal中
        threadLocal.set(userInfoDTO);
        return true;
    }

    /**
     * 执行目标方法之后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoDTO userInfoDTO = threadLocal.get();
        // 如果登录用户不是临时用户，就为其添加cookie
        if (!userInfoDTO.getTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoDTO.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            // 解决跳转页面之后，无法保存cookie
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
}
